/* eslint-disable max-len */
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import fileSaver from 'file-saver';
import * as JSZip from 'jszip';
import * as JSZipUtils from 'jszip-utils';
import { ThemeRouteChangeService } from '../../service/theme-route-change.service';
import { MetadataService } from '../../service/metadata.service';
import { ImportExportService } from '../../service/import-export.service';

@Component({
    selector: 'app-settings-header',
    templateUrl: './settings-header.component.html',
    styleUrls: ['./settings-header.component.css']
})
export class SettingsHeaderComponent implements OnInit {
    // 标记当前的标签
    @Input() current = '';

    @Input() extendCSS = '';

    // 标记下载的内容是否准备好
    contentReady = true;

    private downloadDP = false;

    // 清空css事件
    @Output() clearCSSEvent = new EventEmitter();

    // 编译事件
    @Output() buildThemeEvent = new EventEmitter();

    constructor(
        private themeRouteChangeSer: ThemeRouteChangeService,
        private metadataService: MetadataService,
        private importExportSer: ImportExportService
    ) {}

    ngOnInit() {}

    /**
     * 获取不带后缀的名称
     */
    getFileNameWithoutExt(nameSuffix, themeName = ''): string {
        let result = '';
        const suffix = nameSuffix ? '(' + nameSuffix + ')' : '';
        switch (themeName) {
        case 'framework':
            result = `${themeName}.${this.themeRouteChangeSer.getThemeColor()}${suffix}`;
            break;

        default:
            result = `${this.themeRouteChangeSer.getThemeName()}.${this.themeRouteChangeSer.getThemeColor()}.${this.themeRouteChangeSer.getThemeSize()}${suffix}`;
            break;
        }
        return result;
    }

    /**
     * 下载下拉面板
     * @param ev
     */
    downloadDropdown(ev) {
        ev.stopPropagation();
        this.downloadDP = !this.downloadDP;
    }

    /**
     * 下载两个
     */
    downloadZip() {
        const nameSuffix = this.formatDate(new Date());
        this.downloadFarrisZip(nameSuffix);
        this.downloadFramework(nameSuffix);
    }

    /**
     * 下载文件
     */
    downloadFarrisZip(nameSuffix) {
        nameSuffix = nameSuffix || this.formatDate(new Date());
        const zip = new JSZip();
        this.contentReady = false;
        const tfilePath = `assets/themes/${this.themeRouteChangeSer.getThemeColor()}/${this.themeRouteChangeSer.getThemeSize()}/`;
        const imgsFiles = ['table-norecords.png'];
        const fontsFiles = ['farrisicon.ttf', 'farrisicon-extend.ttf'];
        /**
         * 汇总图片
         */
        const imgZip = zip.folder('imgs');
        imgsFiles.forEach((fileName) => {
            imgZip.file(fileName, JSZipUtils.getBinaryContent(tfilePath + 'imgs/' + fileName));
        });
        /**
         * 汇总字体文件
         */
        fontsFiles.forEach((fileName) => {
            zip.file(fileName, JSZipUtils.getBinaryContent(tfilePath + fileName));
        });
        const fileName = this.getFileNameWithoutExt(nameSuffix, '');
        /**
         * 汇总样式文件
         * 如果没有变化，直接读取资源的farris-all.css
         */
        if (this.metadataService.getModifiedItems().length === 0) {
            zip.file('farris-all.css', JSZipUtils.getBinaryContent(tfilePath + 'farris-all.css'));
        } else {
            zip.file(`farris-all.css`, this.importExportSer.exportCss(), { binary: false });
        }
        /**
         * 生成
         */
        zip.generateAsync({ type: 'blob' }).then((content) => {
            this.contentReady = true;
            fileSaver.saveAs(content, fileName + '.zip');
        });
        this.downloadDP = false;
    }

    downloadFramework(nameSuffix) {
        nameSuffix = nameSuffix || this.formatDate(new Date());
        const zip = new JSZip();
        this.contentReady = false;
        const tfilePath = `assets/themes/framework/${this.themeRouteChangeSer.getThemeColor()}/`;
        const fileName = this.getFileNameWithoutExt(nameSuffix, 'framework');
        /**
         * 汇总样式文件
         * 如果没有变化，直接读取资源的farris-all.css
         */
        if (this.metadataService.getModifiedItems().length === 0) {
            zip.file('gsp-cloud-web.css', JSZipUtils.getBinaryContent(tfilePath + 'gsp-cloud-web.min.css'));
        } else {
            zip.file(`gsp-cloud-web.css`, this.importExportSer.exportCss('framework'), { binary: false });
        }
        /**
         * 生成
         */
        zip.generateAsync({ type: 'blob' }).then((content) => {
            this.contentReady = true;
            fileSaver.saveAs(content, fileName + '.zip');
        });
        this.downloadDP = false;
    }

    /**
     * 更新预览界面
     */
    updatePreview() {
        this.buildThemeEvent.emit();
        this.metadataService.buildAll();
    }

    /**
     * 重置变量
     */
    resetVariables() {
        if (this.current === 'extend') {
            this.clearCSSEvent.emit();
        }
        this.metadataService.resetVariables();
    }

    /**
     * 日期格式转换
     * @param millisecond 毫秒
     * @param template 模板(可选)
     * @example formatDate(new Date(), "YYYY-mm-dd HH:MM:SS") => 2021-11-02 09:39:59
     */
    private formatDate(millisecond, template = 'YYYY-mm-dd HH:MM:SS') {
        let res = '';
        try {
            const date = new Date(millisecond);
            const opt = {
                'Y+': date.getFullYear().toString(), // 年
                'm+': (date.getMonth() + 1).toString(), // 月
                'd+': date.getDate().toString(), // 日
                'H+': date.getHours().toString(), // 时
                'M+': date.getMinutes().toString(), // 分
                'S+': date.getSeconds().toString() // 秒
            };
            template = template || 'YYYY-mm-dd';
            const keys = Object.keys(opt);
            keys.forEach((k) => {
                const ret = new RegExp('(' + k + ')').exec(template);
                if (ret) {
                    template = template.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'));
                }
            });
            res = template;
        } catch (error) {
            console.warn('日期格式化报错', error);
        }
        return res;
    }
}
